//+------------------------------------------------------------------+
//|                                              WaveTheoryGA.mqh |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024"
#property link      ""
#property version   "1.00"
#property strict

#include "SupportResistanceSystem.mqh"

// 五浪理论遗传算法个体结构
struct WaveTheoryIndividual {
    // 波浪识别参数
    double wave1MinAmplitude;      // 第1浪最小幅度
    double wave2RetracementMin;    // 第2浪最小回撤
    double wave2RetracementMax;    // 第2浪最大回撤
    double wave3ExtensionMin;      // 第3浪最小延伸
    double wave3ExtensionMax;      // 第3浪最大延伸
    double wave4RetracementMin;    // 第4浪最小回撤
    double wave4RetracementMax;    // 第4浪最大回撤
    double wave5ExtensionMin;      // 第5浪最小延伸
    
    // 支撑阻力位参数
    double srLookbackPeriod;       // 支撑阻力位回看周期
    double srMinTouchCount;        // 最小触及次数
    double srTolerance;            // 容差
    double srStrengthThreshold;    // 强度阈值
    double fibLevels[5];           // 斐波那契比例
    double pivotPeriod;            // 轴心位周期
    
    // 右侧交易参数
    double breakoutConfirmation;   // 突破确认比例
    double retestConfirmation;     // 回踩确认比例
    double minBreakoutStrength;    // 最小突破强度
    double retestBars;             // 回踩确认K线数
    
    // 技术指标权重
    double rsiWeight;              // RSI权重
    double maWeight;               // MA权重
    double volumeWeight;           // 成交量权重
    double adxWeight;              // ADX权重
    
    // 适应度
    double fitness;                // 适应度分数
    double winRate;                // 胜率
    double profitFactor;           // 盈亏比
    double maxDrawdown;            // 最大回撤
    double sharpeRatio;            // 夏普比率
};

// 五浪理论遗传算法类
class CWaveTheoryGA {
private:
    WaveTheoryIndividual m_population[];  // 种群
    int m_populationSize;                 // 种群大小
    int m_generations;                    // 代数
    int m_currentGeneration;              // 当前代数
    
    // 遗传算法参数
    double m_mutationRate;                // 变异率
    double m_crossoverRate;               // 交叉率
    double m_elitismRate;                 // 精英比例
    
    // 最佳个体
    WaveTheoryIndividual m_bestIndividual;
    double m_bestFitness;
    
    // 支撑阻力位分析器
    CSupportResistanceAnalysis m_srAnalysis;
    
    // 历史数据
    double m_historicalHigh[];
    double m_historicalLow[];
    double m_historicalClose[];
    double m_historicalVolume[];
    int m_dataSize;
    
    // 交易结果
    struct TradeResult {
        datetime time;
        double entryPrice;
        double exitPrice;
        double profit;
        bool isWin;
        string reason;
    };
    
    TradeResult m_tradeResults[];
    int m_tradeCount;
    
public:
    // 构造函数
    CWaveTheoryGA() {
        m_populationSize = 50;
        m_generations = 100;
        m_currentGeneration = 0;
        m_mutationRate = 0.1;
        m_crossoverRate = 0.8;
        m_elitismRate = 0.1;
        m_bestFitness = 0;
        m_tradeCount = 0;
    }
    
    // 初始化
    bool Initialize(int populationSize = 50, int generations = 100) {
        m_populationSize = populationSize;
        m_generations = generations;
        
        // 初始化种群
        ArrayResize(m_population, m_populationSize);
        
        // 初始化支撑阻力位分析器
        if(!m_srAnalysis.Initialize(100, 2, 0.001)) {
            Print("Failed to initialize Support Resistance Analysis");
            return false;
        }
        
        // 初始化历史数据
        InitializeHistoricalData();
        
        return true;
    }
    
    // 运行遗传算法
    bool RunOptimization() {
        Print("Starting Wave Theory GA optimization...");
        
        // 初始化种群
        InitializePopulation();
        
        // 主循环
        for(int generation = 0; generation < m_generations; generation++) {
            m_currentGeneration = generation;
            
            // 评估适应度
            EvaluateFitness();
            
            // 选择
            Selection();
            
            // 交叉
            Crossover();
            
            // 变异
            Mutation();
            
            // 精英保留
            Elitism();
            
            // 输出进度
            if(generation % 10 == 0) {
                Print("Generation ", generation, " - Best Fitness: ", m_bestFitness);
            }
        }
        
        Print("GA optimization completed. Best fitness: ", m_bestFitness);
        return true;
    }
    
    // 获取最佳个体
    bool GetBestIndividual(WaveTheoryIndividual &individual) {
        if(m_bestFitness <= 0) return false;
        
        individual = m_bestIndividual;
        return true;
    }
    
    // 使用最佳个体进行交易
    bool TradeWithBestIndividual() {
        if(m_bestFitness <= 0) return false;
        
        // 使用最佳个体的参数进行交易
        return ExecuteTradingStrategy(m_bestIndividual);
    }
    
private:
    // 初始化历史数据
    void InitializeHistoricalData() {
        int bars = 1000; // 获取1000根K线数据
        
        ArrayResize(m_historicalHigh, bars);
        ArrayResize(m_historicalLow, bars);
        ArrayResize(m_historicalClose, bars);
        ArrayResize(m_historicalVolume, bars);
        
        ArraySetAsSeries(m_historicalHigh, true);
        ArraySetAsSeries(m_historicalLow, true);
        ArraySetAsSeries(m_historicalClose, true);
        ArraySetAsSeries(m_historicalVolume, true);
        
        if(CopyHigh(Symbol(), PERIOD_CURRENT, 0, bars, m_historicalHigh) != bars ||
           CopyLow(Symbol(), PERIOD_CURRENT, 0, bars, m_historicalLow) != bars ||
           CopyClose(Symbol(), PERIOD_CURRENT, 0, bars, m_historicalClose) != bars ||
           CopyTickVolume(Symbol(), PERIOD_CURRENT, 0, bars, m_historicalVolume) != bars) {
            Print("Failed to copy historical data");
            return;
        }
        
        m_dataSize = bars;
        Print("Historical data initialized: ", bars, " bars");
    }
    
    // 初始化种群
    void InitializePopulation() {
        for(int i = 0; i < m_populationSize; i++) {
            InitializeIndividual(m_population[i]);
        }
    }
    
    // 初始化个体
    void InitializeIndividual(WaveTheoryIndividual &individual) {
        // 波浪识别参数
        individual.wave1MinAmplitude = 0.0001 + (MathRand() % 50) / 10000.0; // 0.0001-0.005
        individual.wave2RetracementMin = 0.236 + (MathRand() % 20) / 100.0;  // 0.236-0.436
        individual.wave2RetracementMax = 0.618 + (MathRand() % 20) / 100.0;  // 0.618-0.818
        individual.wave3ExtensionMin = 1.0 + (MathRand() % 30) / 100.0;      // 1.0-1.3
        individual.wave3ExtensionMax = 1.618 + (MathRand() % 40) / 100.0;    // 1.618-2.018
        individual.wave4RetracementMin = 0.236 + (MathRand() % 15) / 100.0;  // 0.236-0.386
        individual.wave4RetracementMax = 0.382 + (MathRand() % 15) / 100.0;  // 0.382-0.532
        individual.wave5ExtensionMin = 0.618 + (MathRand() % 30) / 100.0;    // 0.618-0.918
        
        // 支撑阻力位参数
        individual.srLookbackPeriod = 50 + (MathRand() % 150);               // 50-200
        individual.srMinTouchCount = 1 + (MathRand() % 4);                   // 1-5
        individual.srTolerance = 0.0005 + (MathRand() % 20) / 10000.0;       // 0.0005-0.0025
        individual.srStrengthThreshold = 0.3 + (MathRand() % 40) / 100.0;    // 0.3-0.7
        individual.pivotPeriod = 10 + (MathRand() % 30);                     // 10-40
        
        // 斐波那契比例
        individual.fibLevels[0] = 0.236 + (MathRand() % 10) / 1000.0;        // 0.236-0.246
        individual.fibLevels[1] = 0.382 + (MathRand() % 10) / 1000.0;        // 0.382-0.392
        individual.fibLevels[2] = 0.500 + (MathRand() % 10) / 1000.0;        // 0.500-0.510
        individual.fibLevels[3] = 0.618 + (MathRand() % 10) / 1000.0;        // 0.618-0.628
        individual.fibLevels[4] = 0.786 + (MathRand() % 10) / 1000.0;        // 0.786-0.796
        
        // 右侧交易参数
        individual.breakoutConfirmation = 0.001 + (MathRand() % 30) / 10000.0; // 0.001-0.004
        individual.retestConfirmation = 0.001 + (MathRand() % 30) / 10000.0;    // 0.001-0.004
        individual.minBreakoutStrength = 0.4 + (MathRand() % 40) / 100.0;       // 0.4-0.8
        individual.retestBars = 1 + (MathRand() % 5);                           // 1-6
        
        // 技术指标权重
        individual.rsiWeight = 0.1 + (MathRand() % 40) / 100.0;                // 0.1-0.5
        individual.maWeight = 0.1 + (MathRand() % 40) / 100.0;                 // 0.1-0.5
        individual.volumeWeight = 0.1 + (MathRand() % 30) / 100.0;             // 0.1-0.4
        individual.adxWeight = 0.1 + (MathRand() % 30) / 100.0;                // 0.1-0.4
        
        // 归一化权重
        double totalWeight = individual.rsiWeight + individual.maWeight + 
                           individual.volumeWeight + individual.adxWeight;
        individual.rsiWeight /= totalWeight;
        individual.maWeight /= totalWeight;
        individual.volumeWeight /= totalWeight;
        individual.adxWeight /= totalWeight;
        
        individual.fitness = 0;
    }
    
    // 评估适应度
    void EvaluateFitness() {
        for(int i = 0; i < m_populationSize; i++) {
            // 使用个体参数进行回测
            m_population[i].fitness = EvaluateIndividual(m_population[i]);
            
            // 更新最佳个体
            if(m_population[i].fitness > m_bestFitness) {
                m_bestFitness = m_population[i].fitness;
                m_bestIndividual = m_population[i];
            }
        }
    }
    
    // 评估个体
    double EvaluateIndividual(WaveTheoryIndividual &individual) {
        // 重置交易结果
        m_tradeCount = 0;
        ArrayResize(m_tradeResults, 0);
        
        // 使用个体参数进行回测
        if(!ExecuteTradingStrategy(individual)) {
            return 0;
        }
        
        // 计算适应度指标
        CalculateFitnessMetrics(individual);
        
        // 综合适应度计算
        double fitness = individual.winRate * 0.3 +                    // 胜率权重30%
                        individual.profitFactor * 0.3 +                // 盈亏比权重30%
                        (1.0 - individual.maxDrawdown) * 0.2 +         // 回撤权重20%
                        individual.sharpeRatio * 0.2;                  // 夏普比率权重20%
        
        return fitness;
    }
    
    // 执行交易策略
    bool ExecuteTradingStrategy(WaveTheoryIndividual &individual) {
        // 使用个体参数重新初始化支撑阻力位分析器
        m_srAnalysis.Initialize((int)individual.srLookbackPeriod, 
                               (int)individual.srMinTouchCount, 
                               individual.srTolerance);
        
        // 分析支撑阻力位
        if(!m_srAnalysis.AnalyzeSupportResistance(m_historicalHigh, m_historicalLow, 
                                                 m_historicalClose, m_historicalVolume, m_dataSize)) {
            return false;
        }
        
        // 模拟交易
        for(int i = 100; i < m_dataSize - 10; i++) {
            // 检查波浪模式
            if(IsWavePattern(m_historicalHigh, m_historicalLow, m_historicalClose, i, individual)) {
                // 检查支撑阻力位信号
                CheckSupportResistanceSignals(i, individual);
            }
        }
        
        return m_tradeCount > 0;
    }
    
    // 检查波浪模式
    bool IsWavePattern(const double &high[], const double &low[], const double &close[], 
                      int index, WaveTheoryIndividual &individual) {
        // 简化的五浪模式识别
        if(index < 50) return false;
        
        // 检查第1浪
        if(!IsWave1(high, low, close, index - 40, index - 30, individual)) return false;
        
        // 检查第2浪
        if(!IsWave2(high, low, close, index - 30, index - 20, individual)) return false;
        
        // 检查第3浪
        if(!IsWave3(high, low, close, index - 20, index - 10, individual)) return false;
        
        // 检查第4浪
        if(!IsWave4(high, low, close, index - 10, index, individual)) return false;
        
        // 检查第5浪
        if(!IsWave5(high, low, close, index, index + 10, individual)) return false;
        
        return true;
    }
    
    // 检查第1浪
    bool IsWave1(const double &high[], const double &low[], const double &close[], 
                int start, int end, WaveTheoryIndividual &individual) {
        double amplitude = high[end] - low[start];
        return amplitude >= individual.wave1MinAmplitude;
    }
    
    // 检查第2浪
    bool IsWave2(const double &high[], const double &low[], const double &close[], 
                int start, int end, WaveTheoryIndividual &individual) {
        double wave1High = high[start];
        double wave1Low = low[start];
        double wave2Low = low[end];
        
        double retracement = (wave1High - wave2Low) / (wave1High - wave1Low);
        
        return retracement >= individual.wave2RetracementMin && 
               retracement <= individual.wave2RetracementMax;
    }
    
    // 检查第3浪
    bool IsWave3(const double &high[], const double &low[], const double &close[], 
                int start, int end, WaveTheoryIndividual &individual) {
        double wave2Low = low[start];
        double wave3High = high[end];
        double wave1High = high[start - 10];
        
        double extension = (wave3High - wave2Low) / (wave1High - wave2Low);
        
        return extension >= individual.wave3ExtensionMin && 
               extension <= individual.wave3ExtensionMax;
    }
    
    // 检查第4浪
    bool IsWave4(const double &high[], const double &low[], const double &close[], 
                int start, int end, WaveTheoryIndividual &individual) {
        double wave3High = high[start];
        double wave4Low = low[end];
        double wave2Low = low[start - 10];
        
        double retracement = (wave3High - wave4Low) / (wave3High - wave2Low);
        
        return retracement >= individual.wave4RetracementMin && 
               retracement <= individual.wave4RetracementMax;
    }
    
    // 检查第5浪
    bool IsWave5(const double &high[], const double &low[], const double &close[], 
                int start, int end, WaveTheoryIndividual &individual) {
        double wave4Low = low[start];
        double wave5High = high[end];
        double wave3High = high[start - 10];
        
        double extension = (wave5High - wave4Low) / (wave3High - wave4Low);
        
        return extension >= individual.wave5ExtensionMin;
    }
    
    // 检查支撑阻力位信号
    void CheckSupportResistanceSignals(int index, WaveTheoryIndividual &individual) {
        double currentPrice = m_historicalClose[index];
        double previousPrice = m_historicalClose[index - 1];
        
        // 检查阻力位突破
        if(m_srAnalysis.IsLevelBreakout(currentPrice, previousPrice, LEVEL_RESISTANCE)) {
            // 检查突破强度
            if(GetBreakoutStrength(index) >= individual.minBreakoutStrength) {
                // 检查回踩确认
                if(CheckRetestConfirmation(index, currentPrice, LEVEL_RESISTANCE, individual)) {
                    AddTradeResult(index, currentPrice, currentPrice * 1.02, true, "Wave Resistance Breakout");
                }
            }
        }
        
        // 检查支撑位突破
        if(m_srAnalysis.IsLevelBreakout(currentPrice, previousPrice, LEVEL_SUPPORT)) {
            // 检查突破强度
            if(GetBreakoutStrength(index) >= individual.minBreakoutStrength) {
                // 检查回踩确认
                if(CheckRetestConfirmation(index, currentPrice, LEVEL_SUPPORT, individual)) {
                    AddTradeResult(index, currentPrice, currentPrice * 0.98, false, "Wave Support Breakout");
                }
            }
        }
    }
    
    // 获取突破强度
    double GetBreakoutStrength(int index) {
        // 基于成交量和价格变动计算突破强度
        double volumeRatio = m_historicalVolume[index] / GetAverageVolume(index - 20, index);
        double priceChange = MathAbs(m_historicalClose[index] - m_historicalClose[index - 1]) / m_historicalClose[index - 1];
        
        return volumeRatio * priceChange;
    }
    
    // 检查回踩确认
    bool CheckRetestConfirmation(int index, double breakoutPrice, ENUM_LEVEL_TYPE type, 
                                WaveTheoryIndividual &individual) {
        int confirmBars = (int)individual.retestBars;
        
        for(int i = 1; i <= confirmBars && (index + i) < m_dataSize; i++) {
            double currentPrice = m_historicalClose[index + i];
            
            if(type == LEVEL_RESISTANCE) {
                // 阻力位突破后回踩确认
                if(currentPrice < breakoutPrice && 
                   MathAbs(currentPrice - breakoutPrice) <= individual.retestConfirmation * breakoutPrice) {
                    return true;
                }
            } else if(type == LEVEL_SUPPORT) {
                // 支撑位突破后回踩确认
                if(currentPrice > breakoutPrice && 
                   MathAbs(currentPrice - breakoutPrice) <= individual.retestConfirmation * breakoutPrice) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    // 添加交易结果
    void AddTradeResult(int index, double entryPrice, double exitPrice, bool isBuy, string reason) {
        ArrayResize(m_tradeResults, m_tradeCount + 1);
        
        m_tradeResults[m_tradeCount].time = TimeCurrent();
        m_tradeResults[m_tradeCount].entryPrice = entryPrice;
        m_tradeResults[m_tradeCount].exitPrice = exitPrice;
        m_tradeResults[m_tradeCount].isWin = isBuy ? (exitPrice > entryPrice) : (exitPrice < entryPrice);
        m_tradeResults[m_tradeCount].profit = isBuy ? (exitPrice - entryPrice) : (entryPrice - exitPrice);
        m_tradeResults[m_tradeCount].reason = reason;
        
        m_tradeCount++;
    }
    
    // 计算适应度指标
    void CalculateFitnessMetrics(WaveTheoryIndividual &individual) {
        if(m_tradeCount == 0) {
            individual.winRate = 0;
            individual.profitFactor = 0;
            individual.maxDrawdown = 1;
            individual.sharpeRatio = 0;
            return;
        }
        
        // 计算胜率
        int wins = 0;
        for(int i = 0; i < m_tradeCount; i++) {
            if(m_tradeResults[i].isWin) wins++;
        }
        individual.winRate = (double)wins / m_tradeCount;
        
        // 计算盈亏比
        double totalProfit = 0, totalLoss = 0;
        for(int i = 0; i < m_tradeCount; i++) {
            if(m_tradeResults[i].isWin) {
                totalProfit += m_tradeResults[i].profit;
            } else {
                totalLoss += MathAbs(m_tradeResults[i].profit);
            }
        }
        individual.profitFactor = (totalLoss > 0) ? (totalProfit / totalLoss) : 0;
        
        // 计算最大回撤
        individual.maxDrawdown = CalculateMaxDrawdown();
        
        // 计算夏普比率
        individual.sharpeRatio = CalculateSharpeRatio();
    }
    
    // 计算最大回撤
    double CalculateMaxDrawdown() {
        double peak = 0;
        double maxDrawdown = 0;
        double equity = 1000; // 初始资金
        
        for(int i = 0; i < m_tradeCount; i++) {
            equity += m_tradeResults[i].profit;
            
            if(equity > peak) {
                peak = equity;
            }
            
            double drawdown = (peak - equity) / peak;
            if(drawdown > maxDrawdown) {
                maxDrawdown = drawdown;
            }
        }
        
        return maxDrawdown;
    }
    
    // 计算夏普比率
    double CalculateSharpeRatio() {
        if(m_tradeCount < 2) return 0;
        
        // 计算平均收益
        double totalReturn = 0;
        for(int i = 0; i < m_tradeCount; i++) {
            totalReturn += m_tradeResults[i].profit;
        }
        double avgReturn = totalReturn / m_tradeCount;
        
        // 计算标准差
        double variance = 0;
        for(int i = 0; i < m_tradeCount; i++) {
            variance += MathPow(m_tradeResults[i].profit - avgReturn, 2);
        }
        double stdDev = MathSqrt(variance / (m_tradeCount - 1));
        
        return (stdDev > 0) ? (avgReturn / stdDev) : 0;
    }
    
    // 获取平均成交量
    double GetAverageVolume(int start, int end) {
        double totalVolume = 0;
        int count = 0;
        
        for(int i = start; i <= end && i < m_dataSize; i++) {
            totalVolume += m_historicalVolume[i];
            count++;
        }
        
        return (count > 0) ? (totalVolume / count) : 1;
    }
    
    // 选择
    void Selection() {
        // 轮盘赌选择
        WaveTheoryIndividual newPopulation[];
        ArrayResize(newPopulation, m_populationSize);
        
        // 计算总适应度
        double totalFitness = 0;
        for(int i = 0; i < m_populationSize; i++) {
            totalFitness += m_population[i].fitness;
        }
        
        // 选择个体
        for(int i = 0; i < m_populationSize; i++) {
            double random = MathRand() / 32768.0 * totalFitness;
            double cumulative = 0;
            
            for(int j = 0; j < m_populationSize; j++) {
                cumulative += m_population[j].fitness;
                if(cumulative >= random) {
                    newPopulation[i] = m_population[j];
                    break;
                }
            }
        }
        
        // 更新种群
        for(int i = 0; i < m_populationSize; i++) {
            m_population[i] = newPopulation[i];
        }
    }
    
    // 交叉
    void Crossover() {
        for(int i = 0; i < m_populationSize - 1; i += 2) {
            if(MathRand() / 32768.0 < m_crossoverRate) {
                CrossoverIndividuals(m_population[i], m_population[i + 1]);
            }
        }
    }
    
    // 交叉两个个体
    void CrossoverIndividuals(WaveTheoryIndividual &individual1, WaveTheoryIndividual &individual2) {
        // 波浪参数交叉
        if(MathRand() % 2 == 0) {
            double temp = individual1.wave2RetracementMin;
            individual1.wave2RetracementMin = individual2.wave2RetracementMin;
            individual2.wave2RetracementMin = temp;
        }
        
        if(MathRand() % 2 == 0) {
            double temp = individual1.wave3ExtensionMin;
            individual1.wave3ExtensionMin = individual2.wave3ExtensionMin;
            individual2.wave3ExtensionMin = temp;
        }
        
        // 支撑阻力位参数交叉
        if(MathRand() % 2 == 0) {
            double temp = individual1.srTolerance;
            individual1.srTolerance = individual2.srTolerance;
            individual2.srTolerance = temp;
        }
        
        // 技术指标权重交叉
        if(MathRand() % 2 == 0) {
            double temp = individual1.rsiWeight;
            individual1.rsiWeight = individual2.rsiWeight;
            individual2.rsiWeight = temp;
        }
    }
    
    // 变异
    void Mutation() {
        for(int i = 0; i < m_populationSize; i++) {
            if(MathRand() / 32768.0 < m_mutationRate) {
                MutateIndividual(m_population[i]);
            }
        }
    }
    
    // 变异个体
    void MutateIndividual(WaveTheoryIndividual &individual) {
        // 随机选择参数进行变异
        int mutationType = MathRand() % 10;
        
        switch(mutationType) {
            case 0:
                individual.wave2RetracementMin += (MathRand() % 20 - 10) / 1000.0;
                break;
            case 1:
                individual.wave3ExtensionMin += (MathRand() % 20 - 10) / 1000.0;
                break;
            case 2:
                individual.srTolerance += (MathRand() % 10 - 5) / 10000.0;
                break;
            case 3:
                individual.rsiWeight += (MathRand() % 20 - 10) / 1000.0;
                break;
            case 4:
                individual.breakoutConfirmation += (MathRand() % 10 - 5) / 10000.0;
                break;
            case 5:
                individual.fibLevels[MathRand() % 5] += (MathRand() % 10 - 5) / 1000.0;
                break;
            case 6:
                individual.srLookbackPeriod += MathRand() % 20 - 10;
                break;
            case 7:
                individual.minBreakoutStrength += (MathRand() % 20 - 10) / 1000.0;
                break;
            case 8:
                individual.retestBars += MathRand() % 3 - 1;
                break;
            case 9:
                individual.maWeight += (MathRand() % 20 - 10) / 1000.0;
                break;
        }
        
        // 确保参数在合理范围内
        ValidateIndividual(individual);
    }
    
    // 验证个体参数
    void ValidateIndividual(WaveTheoryIndividual &individual) {
        // 波浪参数验证
        individual.wave2RetracementMin = MathMax(0.1, MathMin(0.5, individual.wave2RetracementMin));
        individual.wave2RetracementMax = MathMax(0.5, MathMin(0.9, individual.wave2RetracementMax));
        individual.wave3ExtensionMin = MathMax(0.8, MathMin(1.5, individual.wave3ExtensionMin));
        individual.wave3ExtensionMax = MathMax(1.5, MathMin(2.5, individual.wave3ExtensionMax));
        
        // 支撑阻力位参数验证
        individual.srLookbackPeriod = MathMax(20, MathMin(500, (int)individual.srLookbackPeriod));
        individual.srMinTouchCount = MathMax(1, MathMin(10, (int)individual.srMinTouchCount));
        individual.srTolerance = MathMax(0.0001, MathMin(0.01, individual.srTolerance));
        
        // 技术指标权重验证
        individual.rsiWeight = MathMax(0.0, MathMin(1.0, individual.rsiWeight));
        individual.maWeight = MathMax(0.0, MathMin(1.0, individual.maWeight));
        individual.volumeWeight = MathMax(0.0, MathMin(1.0, individual.volumeWeight));
        individual.adxWeight = MathMax(0.0, MathMin(1.0, individual.adxWeight));
        
        // 归一化权重
        double totalWeight = individual.rsiWeight + individual.maWeight + 
                           individual.volumeWeight + individual.adxWeight;
        if(totalWeight > 0) {
            individual.rsiWeight /= totalWeight;
            individual.maWeight /= totalWeight;
            individual.volumeWeight /= totalWeight;
            individual.adxWeight /= totalWeight;
        }
    }
    
    // 精英保留
    void Elitism() {
        int eliteCount = (int)(m_populationSize * m_elitismRate);
        
        // 找到最佳个体
        int bestIndex = 0;
        for(int i = 1; i < m_populationSize; i++) {
            if(m_population[i].fitness > m_population[bestIndex].fitness) {
                bestIndex = i;
            }
        }
        
        // 将最佳个体复制到种群末尾
        if(bestIndex != m_populationSize - 1) {
            m_population[m_populationSize - 1] = m_population[bestIndex];
        }
    }
}; 